define(function(require, exports){
	var $ = require("jquery");
	var pubjs = require('pubjs');
	var view  = require('@base/view');
	var util = require('util');
	var utilDSP = require('modules/common');

	var List = view.container.extend({
		init:function(config){
			var userData = pubjs.getUserCurrent();
			// 有对接的dsp的账号才有查看模版的按钮。
			config = pubjs.conf(config, {
				'class': 'P-whisky',
				'urlBegin': 'whisky/start',
				'urlPause': 'whisky/pause',
				'urlDelete': 'whisky/remove',
				'urlRecover': 'whisky/recover',
				'urlNameReplace': 'whisky/nameReplace',
				'urlDownload': '/api/dsp/download/whisky/',
				'addHrefBrand': 'serving/whiskyEdit',
				'vModel':{
					'view': {
						'addButton': pubjs.checkRight('whisky.add')
					},
					'vmClickAdd': this.eventClickAdd
				}
			});
			this.Super('init', arguments);
		},
		afterBuild:function(){
			this.append($([
				'<div class="M-formHead">',
					'<button v-show="view.addButton" class="btn btn-primary" v-on:click="vmClickAdd">'+LANG('新建落地页')+'</button>',
					'<span class="fr" pub-name="date" pub-mod="@base/common/date.dateRangeNew"/>',
				'</div>',
				'<div class="cl" pub-name="grid" pub-mod="whisky/grid/whisky.base"/>'
			].join('')));

			this.vm.mount();

			var c = this.getConfig();

			var config = {
				grid: {
					hasMenu: true,
					hasBatch: true,
					hasSelect: true,
					hasSwitch: false,
					hasAutoRefresh: true,
					hasSearch: true,
					hasExport: pubjs.checkRight('whisky.export'),
					param: {
						AdvertiserId: +util.getQueryString('aderId'),
						PlanId: +util.getQueryString('planId'),
						CampaignId: +util.getQueryString('campaignId')
					}
				},
				date:{
					pos: 'bR'
				}
			};
			this.buildFromTemplate(config);

			this.createAsync('slotSidebar', '@layout/v1/sidebar.base', {
				'target': c.targetSidebar,
				'items': [
					{'name': 'status', 'uri':'modules/sideBarBase.radio', 'config': {
						'title': LANG('状态：'),
						'data': [
							{id: 0, name: LANG('所有')},
							{id: -1, name: LANG('未归档')},
							{id: -2, name: LANG('已归档')},
							{id: 1, name: LANG('进行中')},
							{id: 2, name: LANG('已暂停')}
						],
						'value': 0
					}},
					{'name': 'metrics', 'uri':'modules/sideBarBase.metrics', 'config': {
						'metrics': ["{back}","{conversion}"]
					}}
				]
			});
		},
		eventClickAdd: function(ev){
			var c = this.getConfig();
			pubjs.controller.navigate(c.addHrefBrand + utilDSP.getBrandSearch());
		},
		// 批量操作-下拉菜单界面
		onBatchShow: function(ev){
			var result = [];
			var setSubs = [];
			if (pubjs.checkRight('whisky.nameReplace')) {
				setSubs.push({id: 'nameReplace', name: LANG('落地页名称关键词替换') });
			}

			if (setSubs.length) {
				result.push({id: 'set', name: LANG('设置'), subs: setSubs});
			}

			if (pubjs.checkRight('whisky.pause')) {
				result.push({id: 'pause', name: LANG('暂停')});
			}

			if (pubjs.checkRight('whisky.start')) {
				result.push({id: 'start', name: LANG('开始')});
			}

			if (pubjs.checkRight('whisky.remove')) {
				result.push({id: 'delete', name: LANG('归档')});
			}

			if (pubjs.checkRight('whisky.recover')) {
				result.push({id: 'recover', name: LANG('还原')});
			}

			if (pubjs.checkRight('whisky.export')) {
				result.push({id: 'export', name: LANG('导出')});
			}

			if(!result.length)
			{
				result.push({id: '', name: LANG('没有权限')});
			}
			ev.returnValue = result;
			return false;
		},
		// 批量操作-响应菜单操作
		onBatchSelect: function(ev){
			var self = this;
			var data = ev.param[0];
			var ids = ev.param[1].join();
			if(!ids) {
				pubjs.alert(LANG('请先选择落地页'));
				return false;
			}
			var c = this.getConfig();
			switch(data.key){
				case 'nameReplace':
					self.nameReplace({'id': ids });
				break;
				case 'start':
					self.send(c.urlBegin, {'id': ids }, 'afterBatch');
				break;
				case 'pause':
					self.send(c.urlPause, {'id': ids }, 'afterBatch');
				break;
				case 'delete':
					pubjs.confirm(LANG('确认删除以下落地页 %1 吗', ids), function(state) {
						if(state)
						{
							self.send(c.urlDelete, {'id': ids }, 'afterBatch');
						}
					});
				break;
				case 'recover':
					self.send(c.urlRecover, {'id': ids }, 'afterBatch');
				break;
				case 'export':
					var url = utilDSP.getExportApi(this.get('grid'), ids);
					window.location.href = url;
				break;
			}
			return false;
		},
		send: function(url, param, cbName)
		{
			if(url)
			{
				pubjs.loading.show();
				var self = this;
				pubjs.mc.send(url, param, function(err) {
					pubjs.loading.hide();
					if(err)
					{
						return pubjs.alert(err.message);
					}

					pubjs.alert(LANG('操作成功'));
					self[cbName || 'reload'].apply(self, arguments);
				});
			}
		},
		afterBatch: function()
		{
			this.$.grid.setSelectRowIds([]).reload();
		},
		// 操作菜单-下拉菜单界面
		onOperateMenuShow: function(ev){
			var param = ev.param;
			var result = [];

			if(!param.IsDeleted)
			{
				if (param.Status === 1 && pubjs.checkRight('whisky.pause')) {
					result.push({id: 'pause', name: LANG('暂停')});
				}

				if (param.Status !== 1 && pubjs.checkRight('whisky.start')) {
					result.push({id: 'start', name: LANG('开始')});
				}

				if (pubjs.checkRight('whisky.remove'))
				{
					result.push({id: 'delete', name: LANG('归档')});
				}

				if (pubjs.checkRight('whisky.info'))
				{
					result.push({id: 'edit', name: LANG('编辑')});
				}

				// 外部链接，自定义物料类型的创意包没有下载
				if ( param.Type === 1 && pubjs.checkRight('whisky.download'))
				{
					result.push({id: 'download', name: LANG('下载')});
				}
			}
			else
			{
				// 已归档的落地页只有'还原'操作
				if (pubjs.checkRight('whisky.recover')) {
					result.push({id: 'recover', name: LANG('还原')});
				}
			}

			if(!result.length)
			{
				result.push({id: '', name: LANG('没有权限')});
			}
			ev.returnValue = result;
			return false;
		},
		// 操作菜单-响应菜单操作
		onOperateMenuSelect: function(ev){
			var op = ev.param[0];
			var data = ev.param[1];
			var c = this.getConfig();
			var self = this;

			switch(op.key){
				case 'start':
					self.send(c.urlBegin, {'id': +data._id });
				break;
				case 'pause':
					self.send(c.urlPause, {'id': +data._id });
				break;
				case 'delete':
					pubjs.confirm(LANG('确认删除落地页 %1 吗', +data._id), function(state) {
						if(state)
						{
							self.send(c.urlDelete, {'id': +data._id });
						}
					});
				break;
				case 'recover':
					self.send(c.urlRecover, {'id': +data._id });
				break;
				case 'edit':

					pubjs.controller.navigate(c.addHrefBrand + '/' + data._id + utilDSP.getBrandSearch());

				break;
				case 'download':
					pubjs.controller.navigate(c.urlDownload + data._id );
				break;
			}
			return false;
		},
		reload: function(){
			this.$.grid.reload({
				AdvertiserId: +util.getQueryString('aderId'),
				PlanId: +util.getQueryString('planId'),
				CampaignId: +util.getQueryString('campaignId')
			});
		},
		nameReplace: function(data){
			var self = this;
			var dlg = self.get('nameReplaceDia');
			if (!dlg){
				self.createAsync('nameReplaceDia','whisky/popwin/nameReplace.base',{
					"layout": {
						"module": '@base/dialog.base'
						,"mask":1
						,"title": LANG('落地页名称关键词替换')
						,'silence': false
						,"width": 500
					}
				},function(mod){
					mod.setData(data).show();
				});
			}
			else{
				dlg.setData(data).show();
			}
		},
		onNameReplace: function(ev) {
			var self = this;
			var param = ev.param;
			var data = param.data;
			var id = param.id;
			var c = self.getConfig();

			if ( id ) {
				pubjs.loading.show();
				pubjs.mc.send(c.urlNameReplace, {
					originalKeyword: data.originalKeyword,
					newKeyword: data.newKeyword,
					id: id
				}, self.afterSave.bind(self));
			}
		},
		afterSave: function(err, data){
			pubjs.loading.hide();
			if (err) {
				return pubjs.alert(err.message || LANG('修改失败'));
			}

			if((data && data.ids) && !data.ids.length)
			{
				pubjs.alert(LANG('修改失败'));
			}
			else
			{
				pubjs.alert(LANG('修改成功'))
			}

			this.reload();
		},
		onSidebarFilter: function(ev){
			var self = this
				,param = {};

			util.each(ev.param, function(item, idx){
				var type = idx
				var id = item.id;
				switch (type) {
					case 'label':
						param.Labels = id;
						break;
					case 'status':
						switch (+id){
							case 0:
							case 1:
							case 2:
								param.Status = +id;
								param.IsDeleted = 0;
								break;
							case -1:
								param.Status = 0;
								param.IsDeleted = 0;
								break;
							case -2:
								param.IsDeleted = 1;
								break;
						}
						break;
					case 'metrics':
						param.metrics_filter = id;
						break;
				}
			});
			self.$.grid.reload(param);
		},
		onSaveWhiskySuccess: function(ev)
		{
			this.reload();

			if (ev.param && ev.param.id)
			{
				this.$.grid.setRowHighlight(ev.param.id);
			}
		}
	});
	exports.base = List;

});